import { createRouter, createWebHashHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

// 路由组件
const Login = () => import('@/views/Login.vue')
const Layout = () => import('@/layouts/DefaultLayout.vue')

// 管理员页面
const AdminDashboard = () => import('@/views/admin/Dashboard.vue')
const ClassManagement = () => import('@/views/admin/ClassManagement.vue')
const StudentManagement = () => import('@/views/admin/StudentManagement.vue')
const TeacherManagement = () => import('@/views/admin/TeacherManagement.vue')
const UserManagement = () => import('@/views/admin/UserManagement.vue')
const AttendanceSettings = () => import('@/views/admin/AttendanceSettings.vue')
const AfterSchoolClassManagement = () => import('@/views/admin/AfterSchoolClassManagement.vue')

// 教师页面
const TeacherDashboard = () => import('@/views/teacher/Dashboard.vue')
const ArrivalManagement = () => import('@/views/teacher/ArrivalManagement.vue')
const DepartureManagement = () => import('@/views/teacher/DepartureManagement.vue')

// 司机页面
const DriverDepartureManagement = () => import('@/views/driver/DepartureManagement.vue')

// 课后老师页面
const AfterSchoolArrivalManagement = () => import('@/views/after_school/ArrivalManagement.vue')

// 通用页面
const Profile = () => import('@/views/Profile.vue')
const NotFound = () => import('@/views/NotFound.vue')

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: Layout,
    meta: { requiresAuth: true },
    children: [
      // 管理员路由
      {
        path: '',
        name: 'Dashboard',
        component: AdminDashboard,
        meta: { roles: ['admin'] }
      },
      {
        path: '/admin/dashboard',
        name: 'AdminDashboard',
        component: AdminDashboard,
        meta: { roles: ['admin'] }
      },
      {
        path: '/admin/classes',
        name: 'ClassManagement',
        component: ClassManagement,
        meta: { roles: ['admin'] }
      },
      {
        path: '/admin/students',
        name: 'StudentManagement',
        component: StudentManagement,
        meta: { roles: ['admin'] }
      },
      {
        path: '/admin/teachers',
        name: 'TeacherManagement',
        component: TeacherManagement,
        meta: { roles: ['admin'] }
      },
      {
        path: '/admin/users',
        name: 'UserManagement',
        component: UserManagement,
        meta: { roles: ['admin'] }
      },
      {
        path: '/admin/attendance-settings',
        name: 'AttendanceSettings',
        component: AttendanceSettings,
        meta: { roles: ['admin'] }
      },
      {
        path: '/admin/after-school-classes',
        name: 'AfterSchoolClassManagement',
        component: AfterSchoolClassManagement,
        meta: { roles: ['admin'] }
      },
      
      // 教师路由
      {
        path: '/teacher/dashboard',
        name: 'TeacherDashboard',
        component: TeacherDashboard,
        meta: { roles: ['teacher'] }
      },
      {
        path: '/teacher/arrival',
        name: 'ArrivalManagement',
        component: ArrivalManagement,
        meta: { roles: ['teacher'] }
      },
      {
        path: '/teacher/departure',
        name: 'DepartureManagement',
        component: DepartureManagement,
        meta: { roles: ['teacher'] }
      },
      
      // 司机路由
      {
        path: '/driver/departure',
        name: 'DriverDepartureManagement',
        component: DriverDepartureManagement,
        meta: { roles: ['driver'] }
      },
      
      // 课后老师路由
      {
        path: '/after-school/arrival',
        name: 'AfterSchoolArrivalManagement',
        component: AfterSchoolArrivalManagement,
        meta: { roles: ['after_school_teacher'] }
      },

      
      // 通用路由
      {
        path: '/profile',
        name: 'Profile',
        component: Profile,
        meta: { roles: ['admin', 'teacher', 'driver', 'after_school_teacher'] }
      },

    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 如果页面需要认证
  if (to.meta.requiresAuth !== false) {
    // 检查是否已登录
    if (!authStore.isAuthenticated) {
      // 未登录，重定向到登录页
      next('/login')
      return
    }
    
    // 验证token是否有效
    const isValid = await authStore.verifyToken()
    if (!isValid) {
      next('/login')
      return
    }
    
    // 检查角色权限
    if (to.meta.roles && !to.meta.roles.includes(authStore.userRole)) {
      // 权限不足，重定向到对应角色的首页
      const role = authStore.userRole
      if (role === 'admin') {
        next('/admin/dashboard')
      } else if (role === 'teacher') {
        next('/teacher/dashboard')
      } else if (role === 'driver') {
        next('/driver/departure')
      } else if (role === 'after_school_teacher') {
        next('/after-school/arrival')
      } else {
        next('/login')
      }
      return
    }
  } else {
    // 如果已登录用户访问登录页，重定向到对应首页
    if (authStore.isAuthenticated && to.path === '/login') {
      const role = authStore.userRole
      if (role === 'admin') {
        next('/admin/dashboard')
      } else if (role === 'teacher') {
        next('/teacher/dashboard')
      } else if (role === 'driver') {
        next('/driver/departure')
      } else if (role === 'after_school_teacher') {
        next('/after-school/arrival')
      } else {
        next('/')
      }
      return
    }
  }
  
  next()
})

export default router
